#!/bin/sh

# This script has been customized for the C3200 Zaurus

# The dialup plugin uses the 'lan-network' script in order to access/install
# system dependent options. System integrators must provide such a script 
# in order to get the dialup plugin working.
#
# This script is a template of 'lan-network'. Complete this script where 
# ##ADD CODE HERE## appears.
#
# The completed script has to be renamed to lan-network and must be copied into
# $QPEDIR/src/plugins/network/lan. The build system automatically installs lan-network
# into the image directory.
#
# For further details how this script is used 
# see $QPEDIR/src/plugins/network/lan/lan.cpp.


###############################
DEBUG=1
LOG=0
LOG_FILE="/tmp/qtopia-network.log"
TMP_FILE="/tmp/lan-intern-network.temp";
RESOLVCONF="/etc/resolv.conf"
###############################


print_debug()
{
    if [ $DEBUG -eq 1 ]; then
        echo "LAN: $1";
    fi
    if [ $LOG -eq 1 ]; then
        echo "LAN: $1" >> $LOG_FILE;
    fi
}

print_options()
{
    echo ;
    echo "Qtopia network interface";
    echo "Usage: lan-network (install|cleanup|start|stop|route)";
    echo "";
    echo "install   <iface name>    dns [DNS1 DNS2] -> sets new dns server";
    echo "                          dhcp -> obtain interface details via DHCP";
    echo "                          static <IP> <subnet> <broadcast> <gateway> -> install interface and use given details";
    echo "                          wireless -essid <ESSID> -mode <Master|Managed|Ad-Hoc>"
    echo "                                   -ap <AP> -bitrate <BITRATE> -nick <NICKNAME>"
    echo "                                   -channel <CHANNEL> -keylength <128|64> -authmode <mode>";
    echo "start     <iface name> -> starts interface";
    echo "stop      <iface name> -> stops interface ";
    echo "cleanup   deletes remaining configuration files";
    echo "route     <iface name> [-gw <gateway IP>] -> the given interface becomes the default gateway for IP traffic (don't pass gateway IP if DHCP used)";
        
    exit 1;
}


# install network configuration and dns server
# parameter: 
#   $1 =>  <iface name e.g. eth1> 
#           $2  => dns  [$3 => dns1 $4 => dns2] ( if no dns IP passed use dhcp to find dns server)
#               => dhcp  (we decided to use DHCP -> no futher options required) 
#               => static  $3 => IP $4 => subnet mask $5 => broadcast addr $6 => Gateway IP
#               => wireless 
#                   the following options can follow the wireless keyword:
#                       [-essid <ESSID>] [-mode <Master|Managed|Ad-Hoc>]
#                       [-ap <AP>] [-bitrate <value>] [-nick <nickname>] [-channel <CHANNEL>]
#                       [-keylength <128|64> ]
#                        
#                       * [-authmode <open|shared> -multikey <defaultKey> <key1> <key2> <key3> <key4>] 
#                       * [-authmode <open|shared> -phrase <passphrase> ]   
#                       * [-authmode <none> -nokey ]  
#                       * [-authmode <WPA-PSK|WPA-EAP> <password> ]
 
install()
{
    # Replace following code if necessary for your system
    
    #dns and confic options
    IFACE=$1;
    shift;
    MODE=$1;
    shift

    case $MODE in 
        dns) 
            print_debug "Installing dns server";
            
            if [ $# -eq 2 ]; then # if no ip passed assume dhcp
               echo "Using given dns server: $1 , $2 ";
               
               echo "nameserver $1" > $TMP_FILE
               echo "nameserver $2" >> $TMP_FILE
            else
               echo "Asking DHCP server for dns details";
               ## ADD CODE HERE ##
               echo > $TMP_FILE
            fi

            mv $TMP_FILE /etc/resolvconf/$IFACE

            rm -f $RESOLVCONF
            ln -s /etc/resolvconf/$IFACE $RESOLVCONF

            ;; 
        dhcp)
            print_debug "Using DHCP to obtain IP, gateway, broadcast and netmask address";

            mkdir -p $HOME/Settings/Network
            NET_OPTIONS=$HOME/Settings/Network/$IFACE

            echo "MODE=dhcp" > $NET_OPTIONS
            ;;
        static)
            print_debug "Using given IP, gateway, broadcast and netmask address";
            print_debug "IP: $1, netmask: $2, broadcast: $3, gateway: $4"
            print_debug "ALL: $@"

            mkdir -p $HOME/Settings/Network
            NET_OPTIONS=$HOME/Settings/Network/$IFACE

            echo "MODE=static" > $NET_OPTIONS
            echo "IPADDR=$1" >> $NET_OPTIONS
            echo "NETMASK=$2" >> $NET_OPTIONS
            echo "BROADCAST=$3" >> $NET_OPTIONS
            echo "GATEWAY=$4" >> $NET_OPTIONS
            ;;
        wireless)
            echo "lan-network wireless $@"
            # no implementation required if wireless lan not used

            mkdir -p $HOME/Settings/Network/wireless
            NET_OPTIONS=$HOME/Settings/Network/wireless/$IFACE
            echo > $NET_OPTIONS

            while [ $# -gt 0 ]; do
                case "$1" in 
                    -mode)
                        shift;
                        echo "WIRELESS_MODE='$1'" >> $NET_OPTIONS
                        ;;
                    -essid)
                        shift;
                        WIRELESS_ESSID=$1
                        echo "WIRELESS_ESSID=$1" >> $NET_OPTIONS
                        ;;
                    -ap)
                        shift;
                        echo "WIRELESS_AP=$1" >> $NET_OPTIONS
                        ;;
                    -bitrate)
                        shift;
                        if [ "$1" = "0" ]; then
                            echo "WIRELESS_BITRATE='auto'" >> $NET_OPTIONS
                            echo "auto detect bitrate"
                        else
                            echo "WIRELESS_BITRATE='$1'" >> $NET_OPTIONS
                            echo "use given bitrate";
                        fi  
                        ;;
                    -nick)
                        shift;
                        echo "WIRELESS_NICK='$1'" >> $NET_OPTIONS
                        ;;
                    -channel)
                        shift;
                        if [ "$1" = "0" ]; then
                            echo "WIRELESS_CHANNEL=''" >> $NET_OPTIONS
                            echo "auto detect channel";
                        else
                            echo "WIRELESS_CHANNEL='$1'" >> $NET_OPTIONS
                            echo "use given channel";
                        fi
                        ;;
                    -keylength)
                        shift;
                        echo "WIRELESS_KEY_LENGTH='$1'" >> $NET_OPTIONS
                        ;;
                    -authmode)
                        shift;
                        echo "WIRELESS_AUTH_MODE=$1" >> $NET_OPTIONS
                        case "$1" in 
                            open|shared|none)
                                ## ADD CODE HERE ##
                                # handle open/shared/none encryptipon
                                shift;
                                if [ "$1" = "-phrase" ]; then
                                    shift;
                                    ## ADD CODE HERE ##
                                    echo "use passphrase";
                                elif [ "$1" = "-nokey" ]; then
                                    shift;
                                    ## ADD CODE HERE ##
                                    print_debug "no password/keys given";
                                elif [ "$1" = "-multikey" ]; then
                                    shift;
                                    echo "using default key: $1" # can be 0-3
                                    ## ADD CODE HERE ##
                                    shift;
                                    ## ADD CODE HERE ##
                                    # read all 4 keys and determine which is default
                                fi
                                ;;
                            WPA-PSK)
                                shift;
                                echo "WIRELESS_PSK=$1" >> $NET_OPTIONS
                                ;;
                            WPA-EAP)
                                shift;
                                ## ADD CODE HERE ##
                                ;;
                        esac
                        ;;
                    *)  
                        print_debug "Unknown option $1";
                        shift
                        ;;
                   
                esac;
                [ $# -gt 0 ] && shift;
            done
            ;;
        *)
            print_debug "Unknown option: $MODE";
            print_options;
            exit 1;
            ;;
    esac
}

# Starts the interface
# parameter:
#   $1 => interface name, e.g. eth1
start()
{
    print_debug "starting interface $1";

    . $HOME/Settings/Network/$1

    if [ -r $HOME/Settings/Network/wireless/$1 ]; then
        echo "Starting wireless"
        set -x
        . $HOME/Settings/Network/wireless/$1
        
        # Generating wpa_supplicant.conf
        [ -d /var/lib/wpa_supplicant ] || mkdir -p /var/lib/wpa_supplicant
        WPACONF=/var/lib/wpa_supplicant/wpa_supplicant.conf
        echo "network={" > $WPACONF
        [ -n "$WIRELESS_ESSID" ] && echo "    ssid=\"$WIRELESS_ESSID\"" >> $WPACONF
        echo "    proto=WPA2 WPA RSN" >> $WPACONF
        [ -n "$WIRELESS_AUTH_MODE" ] && echo "    key_mgmt=$WIRELESS_AUTH_MODE" >> $WPACONF
        echo "    pairwise=CCMP TKIP" >> $WPACONF
        echo "    group=CCMP TKIP" >> $WPACONF
        [ -n "$WIRELESS_PSK" ] && echo "    psk=\"$WIRELESS_PSK\"" >> $WPACONF
        echo "}" >> $WPACONF
        
        /sbin/ifconfig $1 down
        /sbin/ifconfig $1 up

        if [ "$WIRELESS_ESSID" == "" ]; then
           WIRELESS_ESSID = "any"
        fi

        if [ "$WIRELESS_AP" == "" ]; then
				  WIRELESS_AP = "any"
        fi

        if [ "$WIRELESS_BITRATE" != "" ] && [ "$WIRELESS_BITRATE" != "auto" ]; then
            WIRELESS_BITRATE = "${WIRELESS_BITRATE}M auto"
        else
            WIRELESS_BITRATE = "auto"
        fi

#        if [ "$WIRELESS_CHANNEL" != "" ]; then
#            /sbin/iwconfig $1 channel $WIRELESS_CHANNEL
#        fi
        
        if [ "$WIRELESS_AUTH_MODE" = "WPA-PSK" ]; then
            /sbin/wpa_supplicant -i $1 -D socketcf -c $WPACONF -B
        fi
    fi

/sbin/iwconfig $1 essid "$WIRELESS_ESSID" ap "$WIRELESS_AP" channel "$WIRELESS_CHANNEL" rate "$WIRELESS_BITRATE" nick "$WIRELESS_NICK"

    case $MODE in
        dhcp)
            /sbin/udhcpc -i $1 &
            ;;
        static)
            /sbin/ifconfig $1 netmask $NETMASK broadcast $BROADCAST $IPADDR up
            /sbin/route del default
            /sbin/route add default gw $GATEWAY
            ;;
        *)
            ;;
    esac
}

# Stops the interface
# parameter:
#   $1 => interface name, e.g. eth1
stop()
{
    print_debug "stopping interface $1";

    # stop udhcpc for interface
    DHCP_PIDS=$( ps | grep "[u]dhcpc -i $1" | awk '{print $1}' )
    [ -n "$DHCP_PIDS" ] && kill $DHCP_PIDS 2>&1 >/dev/null

    # stop wpa_supplicant for interface
    WPASUP_PIDS=$( ps | grep "[w]pa_supplicant -i $1" | awk '{print $1}' )
    [ -n "$WPASUP_PIDS" ] && kill $WPASUP_PIDS 2>&1 >/dev/null
    
    # bring down interface
    /sbin/ifconfig $1 down
}

# Cleans any existing configuration file. This is called when the user deletes the interface
cleanup()
{
    print_debug "cleaning interface configuration";
    ## ADD CODE HERE ##
    # anything to do?
}

# Changes the routing information so that the given interface becomes the standard gateway.
# This is only called when the interface is running already. If no gateway option is passed
# dhcp lookup is expected
# parameter:
#    route [-gw <gateway IP>]
route()
{
    # Replace following code if necessary for your system
    
    print_debug "changing default route"
    
    if [ $# -gt 2 ]; then
        ## ADD CODE HERE ##
        # gateway address was passed to us
        gateway=$3
    else
        echo "Using DHCP information to find gateway IP";
        ## ADD CODE HERE ##
    fi

    if [ -n "$gateway" ]; then
        print_debug "removing old default route";
        /sbin/route del default;
        print_debug "adding new default route via $1";
        /sbin/route add default gw $gateway;
    fi
}

#######################################
#Parse command line

print_debug "Starting config script for lan plugin";

ACTION=$1;
shift;
case $ACTION in
    start)
        start "$@"
        ;;
    stop)
        stop "$@" 
        ;;
    install)
        install "$@";
        ;;
    cleanup)
        cleanup "$@";
        ;;
    route)
        route "$@";
        ;;
    *)
        print_options;
        exit 1;
        ;;
esac
